package com.baidu.myapplication;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

public class DaemonService extends Service {
    private static final int NOTIFICATION_ID = 18888;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 降低Service的omm_adj，避免被杀掉
        startForegroundCompat();

        // start JobScheduler
        startJobScheduler();

        // player music
        startPlayMusic();

        return START_STICKY;
    }

    private void startPlayMusic() {
        Intent it = new Intent(this, PlayerMusicService.class);
        startService(it);
    }

    private void startJobScheduler() {
        // 定时唤醒的时间间隔，5 分钟
        long WAKE_INTERVAL = 5 * 60 * 1000;
        // 定时检查 WorkService 是否在运行，如果不在运行就把它拉起来
        // Android 5.0+ 使用 JobScheduler
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            jobScheduler.cancelAll();
            JobInfo.Builder jobInfobuilder = new JobInfo.Builder(1024, new ComponentName(getPackageName(), ScheduleService.class.getName()));
            jobInfobuilder.setPeriodic(WAKE_INTERVAL);
            jobInfobuilder.setPersisted(true);
            jobInfobuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
            int schedule = jobScheduler.schedule(jobInfobuilder.build());
            if (schedule <= 0) {
                Log.i("MyApp", "startJobScheduler: error");
            }
        } else {
            // Android 4.4- 使用 AlarmManager
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            Intent alarmIntent = new Intent(this, DaemonService.class);
            PendingIntent pendingIntent = PendingIntent.getService(this, 1024, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            am.cancel(pendingIntent);
            am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + WAKE_INTERVAL, WAKE_INTERVAL, pendingIntent);
        }
    }

    private void startForegroundCompat() {
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2){
            // api 18（4.3）以下
            startForeground(NOTIFICATION_ID, new Notification());
            return;
        }

        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        startForeground(NOTIFICATION_ID, builder.build());

        Intent it = new Intent(this, InnerService.class);
        startService(it);

    }

    public static class InnerService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
        }

        @Override
        public void onDestroy() {
            stopForeground(true);
            super.onDestroy();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {

            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            startForeground(NOTIFICATION_ID, builder.build());
            stopSelf();

            return super.onStartCommand(intent, flags, startId);
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
